<?php

namespace Catmes\LayAdmin\Components;

use Catmes\LayAdmin\Components\LayJs\JsAjax;
use Catmes\LayAdmin\Components\LayJs\JsOpenUrl;
use Catmes\LayAdmin\helpers\HtmlHelper;

class TableItemOperateBtn
{
    const TYPE_OPEN_GET = 'OPEN_GET';
    const TYPE_AJAX_POST = 'AJAX_POST';
    protected $actionType = self::TYPE_OPEN_GET;

    protected $eventName;
    protected $title='编辑';
    protected $msg = '确定删除？';
    protected $btnCssClasses = ['layui-btn', 'layui-btn-xs'];
    protected $btnHtml;

    protected $actionUrl;

    /* @var string $ifJsStr 在指定条件下显示。JS语法判断 */
    protected $ifJsStr='';

    protected $reload=true;

    /* @var TableItemOperate $operate */
    protected $operate;

    public function __construct(TableItemOperate $operate, $actionUrl)
    {
        $this->operate = $operate;
        if(strpos($actionUrl, "\"")===false && strpos($actionUrl, "'")===false){
            // actionUrl 字符串， 不包含 单引号'或双引号"， 则自动在字符串两边加双引号"。
            $actionUrl = "\"" . $actionUrl . "\"";
        }
        $this->actionUrl = $actionUrl;
    }

    public function setIfJs($jsStr):self{
        $this->ifJsStr = $jsStr;
        return $this;
    }
    public function getIfJs():string{
        // 返回值不可以为 null
        return $this->ifJsStr;
    }
    
    /** 操作后自动刷新页面 */
    public function setReload($reload=true):self{
        $this->reload = $reload;
        return $this;
    }

    protected function getBtn($content='编辑', $cssClasses=[], $event=''):self{
        $this->eventName = $event ?: "eventName".mt_rand(11111,99999);
        $options = ['lay-event'=>$this->eventName, 'class'=>$this->btnCssClasses];
        if(!empty($cssClasses)){
            HtmlHelper::addCssClass($options, $cssClasses);
        }
        $this->btnHtml = HtmlHelper::a($content, null, $options);
        return $this;
    }

    public function btnGet($content='编辑', $cssClasses=[], $event='edit'):self{
        $this->actionType = self::TYPE_OPEN_GET;
        //<a class="layui-btn layui-btn-xs layui-btn-normal data-count-edit" lay-event="edit">编辑</a>
        $cssClasses = empty($cssClasses) ? ['layui-btn-normal'] : $cssClasses;
        return $this->getBtn($content, $cssClasses, $event);
    }

    public function btnPost($content='删除', $cssClasses=[], $event='delete'):self{
        $this->actionType = self::TYPE_AJAX_POST;
        //<a class="layui-btn layui-btn-xs layui-btn-danger data-count-delete" lay-event="delete">删除</a>
        $cssClasses = empty($cssClasses) ? ['layui-btn-danger'] : $cssClasses;
        return $this->getBtn($content, $cssClasses, $event);
    }

    public function render():string{
        return $this->btnHtml;
    }

    public function __toString(){
        return $this->render();
    }

    public function renderJs():string{
        if($this->actionType==self::TYPE_AJAX_POST){
            return $this->getJsPostToUrl();
        }
        return $this->getJsOpenByUrl();
    }

    protected function getJsOpenByUrl():string{
        // '/admin/videos/edit?id='+data.id
        $openUrlLayer = new JsOpenUrl($this->actionUrl, $this->title);
        $this->reload && $openUrlLayer->setEndFunc($this->operate->getTable()->getJsReload());
        return <<<JSPTL
            if (obj.event === '{$this->eventName}') {
                {$openUrlLayer}
                return false;
            }
JSPTL;

    }

    public function setConfirmMsg($msg):self{
        $this->msg = $msg;
        return $this;
    }

    protected function getJsPostToUrl():string{
        $template = Template::getInstance();
        $tokenField = $template->getCsrfTokenField();
        $csrfToken = $template->getCsrfToken();

        $jsAjax = new JsAjax($this->actionUrl, ['id'=>'data.id', $tokenField=>$csrfToken]);
        $jsTableReload = $this->operate->getTable()->getJsReload();
        $jsAjax->setJsVars(['data.id'])->setSuccess(JsAjax::JS_RESPONSE.$jsTableReload);
        return <<<JSTPL
            if (obj.event === '{$this->eventName}') {
                layer.confirm('{$this->msg}', function (index) {
                    {$jsAjax}
                    layer.close(index);
                });
            }
JSTPL;

    }

}
